<template>
  <div class="app-container">
    <!-- 模板选择区域 -->
    <el-card class="box-card" shadow="never">
      <div slot="header" class="clearfix">
        <span style="width: 100px;">预算模板选择</span>
        <el-alert
          title="仅显示已启用的模板"
          type="info"
          show-icon
          :closable="false"
          class="info-alert"
        />
      </div>

      <!-- 模板筛选条件 -->
      <el-form :inline="true" class="search-form">
        <el-form-item label="项目类型">
          <el-select v-model="searchParams.projectType" placeholder="全部">
            <el-option label="全部" value=""></el-option>
            <el-option label="纵向" value="纵向"></el-option>
            <el-option label="横向" value="横向"></el-option>
            <!-- 根据实际情况添加其他类型 -->
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadTemplateList">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 模板列表表格 -->
      <el-table
        :data="filteredTemplateList"
        highlight-current-row
        @current-change="handleTemplateSelect"
        style="width: 100%; margin-top: 20px"
        v-loading="loading"
      >
        <el-table-column label="选择" width="70" align="center">
          <template slot-scope="scope">
            <el-radio v-model="selectedTemplateId" :label="scope.row.templateId">&nbsp;</el-radio>
          </template>
        </el-table-column>
        <el-table-column prop="templateName" label="模板名称" min-width="150"></el-table-column>
        <el-table-column prop="projectType" label="项目类型" width="100" align="center"></el-table-column>
        <el-table-column label="状态" width="100" align="center">
          <template slot-scope="scope">
            <el-tag :type="scope.row.enableStatus === 1 ? 'success' : 'danger'">
              {{ scope.row.enableStatus === 1 ? "已启用" : "未启用" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" align="center">
          <template slot-scope="scope">
            <el-button
              type="text"
              size="small"
              @click="previewTemplate(scope.row)"
            >
              预览
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 预算填写区域 -->
    <div v-if="selectedTemplateId">
      <el-divider><i class="el-icon-s-marketing"></i> 预算填写</el-divider>

      <el-alert
        type="info"
        title="填写说明"
        description="请填写预算金额，单位为万元。灰色标记的科目为自动计算行，不可编辑。"
        show-icon
        class="hint-alert"
      />

      <budget-form
        ref="budgetForm"
        :template-id="selectedTemplateId"
        :project-id="projectId"
        :topics="topics"
        :existing-budget-data="existingBudgetData"
        @submit="handleBudgetSubmit"
      />
    </div>

    <!-- 预览弹窗 -->
    <el-dialog
      title="模板预览"
      :visible.sync="previewVisible"
      width="50%"
      top="5vh"
    >
      <template-preview :template="previewData" />
      <div slot="footer" class="dialog-footer">
        <el-button @click="previewVisible = false">关闭</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
import { listTemplate, getTemplate } from "@/api/sci/budgetTemplate";
import BudgetForm from "./components/BudgetForm";
import TemplatePreview from "./components/TemplatePreview";
import { budgetDetailList } from "@/api/sci/budget";

export default {
  name: "BudgetTemplateSelector",
  components: {
    BudgetForm,
    TemplatePreview
  },
  props: {
    projectId: {
      type: [String, Number], // 根据实际类型选择
      default: null
    },
     topics: {  // 修改为传递课题对象数组
      type: Array,
      required: true,
      default: () => []
    }
  },
  data() {
    return {
      // 搜索参数
      searchParams: {
        projectType: "",
      },

      // 所有模板数据
      allTemplateList: [],

      // 当前选中的模板ID
      selectedTemplateId: null,

      // 加载状态
      loading: false,

      // 预览相关数据
      previewVisible: false,
      previewData: null,

      // 提交状态
      isSubmitting: false,

      // 已存在的预算数据
      existingBudgetData: []
    };
  },
  computed: {
    /**
     * 过滤后的模板列表 - 只显示启用状态为1的模板
     */
    filteredTemplateList() {
      return this.allTemplateList.filter(template => template.enableStatus === 1);
    }
  },
  watch: {
    projectId: {
      handler(newVal) {
        if (newVal) {
          this.loadExistingBudgetData();
        }
      },
      immediate: true
    },

    selectedTemplateId: {
      handler(newVal) {
        if (newVal) {
          // 模板变化时重新加载预算数据
          this.$nextTick(() => {
            if (this.$refs.budgetForm && this.existingBudgetData.length > 0) {
              this.$refs.budgetForm.setExistingBudgetData(this.existingBudgetData);
            }
          });
        }
      }
    }
  },
  created() {
    this.loadTemplateList();
  },
  methods: {
    /**
     * 加载已存在的预算数据
     */
    async loadExistingBudgetData() {
      if (!this.projectId) {
        this.existingBudgetData = [];
        return;
      }

      try {
        const response = await budgetDetailList(this.projectId);
        this.existingBudgetData = response.data || [];

        // 如果已经有选中的模板和BudgetForm组件，设置已有数据
        if (this.selectedTemplateId && this.$refs.budgetForm) {
          this.$nextTick(() => {
            this.$refs.budgetForm.setExistingBudgetData(this.existingBudgetData);
          });
        }
      } catch (error) {
        console.error("加载已存在的预算数据失败:", error);
        this.$message.error("加载已存在的预算数据失败");
        this.existingBudgetData = [];
      }
    },

    /**
     * 加载模板列表
     */
   async loadTemplateList() {
      this.loading = true;
      try {
        const res = await listTemplate();
        this.allTemplateList = (res.rows || []).map(template => ({
          ...template,
          // 确保 ID 是数字类型
          templateId: Number(template.templateId),
          enableStatus: Number(template.enableStatus)
        }));

        // 如果没有选中模板，自动选择第一个已启用的模板
        if (!this.selectedTemplateId && this.filteredTemplateList.length > 0) {
          this.selectedTemplateId = this.filteredTemplateList[0].templateId;
        }
      } catch (error) {
        console.error("加载模板列表失败:", error);
        this.$message.error("模板列表加载失败，请重试");
      } finally {
        this.loading = false;
      }
    },

    /**
     * 重置搜索条件
     */
    resetSearch() {
      this.searchParams.projectType = "";
      this.loadTemplateList();
    },

    /**
     * 处理模板选择
     */
    handleTemplateSelect(template) {
      if (template && template.enableStatus === 1) {
        // 确保转换为数字类型
        this.selectedTemplateId = Number(template.templateId);
      }
    },

    /**
     * 预览模板结构
     */
    async previewTemplate(template) {
      try {
        // 获取完整的模板数据，包括sciBudgetSubjectList
        const res = await getTemplate(template.templateId);
        this.previewData = res.data;
        this.previewVisible = true;
      } catch (error) {
        console.error("获取模板详情失败:", error);
        this.$message.error("获取模板详情失败，请重试");
      }
    },

    /**
     * 提交预算数据
     */
    submitBudget() {
      if (this.$refs.budgetForm) {
        this.$refs.budgetForm.handleSubmit();
      }
    },

    /**
     * 处理预算表单提交
     */
    handleBudgetSubmit(budgetData) {
      this.isSubmitting = true;

      // 这里实现提交到后端的逻辑
      console.log("提交的预算数据:", budgetData);

      // 模拟API请求
      setTimeout(() => {
        this.isSubmitting = false;
        this.$message.success("预算数据提交成功");
        this.$emit("submit", budgetData);
      }, 1500);
    },

    /**
     * 重置表单
     */
    resetForm() {
      if (this.$refs.budgetForm) {
        this.$refs.budgetForm.resetForm();
      }
    }
  }
};
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.box-card {
  margin-bottom: 20px;
}

.search-form {
  margin-bottom: -20px;
}

.clearfix {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.info-alert {
  margin-top: 10px;
}

.hint-alert {
  margin-bottom: 20px;
}

.submit-btn {
  margin-top: 30px;
  text-align: center;
}

.el-divider {
  margin: 25px 0;
  background-color: #f0f2f5;
}

.el-divider__text {
  background-color: #fff;
  padding: 0 15px;
  color: #409EFF;
  font-size: 16px;
}
</style>
